package com.CMS.server;

import java.util.Date;
import java.util.List;

import com.CMS.client.UserService;
import com.CMS.server.dao.LanguageDao;
import com.CMS.server.dao.RolDao;
import com.CMS.server.dao.UserDao;
import com.CMS.server.domain.Language;
import com.CMS.server.domain.User;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class RpcUser extends RemoteServiceServlet implements UserService
{

	/**
	 * 
	 */
	private static final long serialVersionUID = -5809661079735095344L;

	public User getUserHabilitado(String user,String pass)
	{
		UserDao loginUser = new UserDao();
		return  loginUser.getUserHabilitado(user, pass);
    }

	@Override
	public List<User> fetch() {
		UserDao dao = new UserDao();
		return dao.getAll();
	}

	@Override
	public void deleteUser(long id) {
		UserDao dao = new UserDao();
		dao.deleteEntity(dao.getEntity(id));
	}

	@Override
	public void create(String alias, String pass, String mail,
			String description, long idRol) {
		
		RolDao rdao = new RolDao();
		LanguageDao ldao = new LanguageDao();
		UserDao dao = new UserDao();
		
		User u = new User();
		u.setDescription(description);
		u.setAlias(alias);
		u.setPassword(pass);
		u.setMail(mail);
		u.setRol(rdao.getEntity(idRol));
		if(u.getLang() == null)
			u.setLang(ldao.getLanguageActive());
		dao.createEntity(u);
	}

	@Override
	public void update(String alias, String pass, String mail,
			String description, String rol, boolean flagDelete, long id) {
		
		RolDao rdao = new RolDao();
		UserDao dao = new UserDao();
		User u = dao.getEntity(id);
		u.setModDate(new Date());
		u.setAlias(alias);
		u.setPassword(pass);
		u.setMail(mail);
		u.setDescription(description);
		u.setRol(rdao.getEntityByDescription(rol));
		u.setFlagDelete(flagDelete);
		if(flagDelete)
			u.setDelDate(new Date());
		dao.updateEntity(u);
	}

	@Override
	public Language getLanguage(String alias) {
		UserDao dao = new UserDao();
		return dao.getUserByAlias(alias).getLang();
	}

	@Override
	public void setLanguage(String alias, String value) {
		UserDao dao = new UserDao();
		LanguageDao ldao = new LanguageDao();
		User u = dao.getUserByAlias(alias);
		u.setLang(ldao.getLanguageByValue(value));
		dao.updateEntity(u);
	}
}
